package be.vanbaelvandaele.tuxremote;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class FileBrowser extends Activity {

	private String currentPath;
	private List<String> currentDirectories = new ArrayList<String>();
	private List<String> currentFiles = new ArrayList<String>();
	private List<String> allItems = new ArrayList<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.filebrowser);

		SshService service = SshService.get(this);
		currentPath = service.executeCommand("pwd");

		TextView currentPathTextView = (TextView) findViewById(R.id.currentPathTextView);
		currentPathTextView.setText(currentPath);

		cd(currentPath);

	}

	private void cd(String path) {
		SshService service = SshService.get(this);
		String directories = service
				.executeCommand("find " + path + " -maxdepth 1 -type d \\( ! -iname \".*\" \\)");
		String files = service
				.executeCommand("find " + path + " -maxdepth 1 -type f \\( ! -iname \".*\" \\)");

		parseResults(directories, files);
		currentPath = path;

		ArrayAdapter<String> directoryAdapter = new ArrayAdapter<String>(this,
				R.layout.simple_list_item_1, allItems);
		ListView directoriesListView = (ListView) findViewById(R.id.directoriesListView);
		directoriesListView.setAdapter(directoryAdapter);
		
		directoriesListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				String item = (String)arg0.getItemAtPosition(arg2);
				if (currentDirectories.contains(item)) {
					cd(currentPath + "/" + item);
				} else {
					// item is a file, open it
					openFile(currentPath + "/" + item);
				}
			}
		});
	}

	protected void openFile(String path) {
		SshService service = SshService.get(this);
		service.executeCommand("export DISPLAY=:0 ; vlc --fullscreen --control dbus " + path);
		finish();
	}

	private void parseResults(String directories, String files) {
		currentDirectories.clear();
		currentFiles.clear();
		allItems.clear();
		
		String[] lines = directories.split("\n");
		for (String line: lines) {
			String[] parts = line.split("/");
			String name = parts[parts.length-1];
			allItems.add(name);
			currentDirectories.add(name);
		}
		
		lines = files.split("\n");
		for (String line: lines) {
			String[] parts = line.split("/");
			String name = parts[parts.length-1];
			allItems.add(name);
			currentFiles.add(name);
		}
		
		Collections.sort(allItems);
	}

}
